package com.zhuoyue.web.controller.system;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;

import com.zhuoyue.common.annotation.Log;
import com.zhuoyue.common.core.controller.BaseController;
import com.zhuoyue.common.core.domain.AjaxResult;
import com.zhuoyue.common.core.page.TableDataInfo;
import com.zhuoyue.common.enums.BusinessType;
import com.zhuoyue.common.utils.poi.ExcelUtil;

import com.zhuoyue.system.domain.dto.ControllerResult;
import com.zhuoyue.system.domain.dto.DevicePoReqDTO;
import com.zhuoyue.system.domain.po.TblDeviceActionPo;
import com.zhuoyue.system.domain.po.TblDevicePo;
import com.zhuoyue.system.domain.vo.TblDeviceActionVo;
import com.zhuoyue.system.domain.vo.TblDeviceVo;
import com.zhuoyue.system.mapper.TblDeviceMapper;
import com.zhuoyue.web.controller.common.ControllerApiResult;
import com.zhuoyue.web.controller.system.util.ApiTokenUtil;
import com.zhuoyue.web.utils.OrgCodeUtils;
//import io.jsonwebtoken.security.Keys;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import com.zhuoyue.system.service.ITblDeviceService;
import org.springframework.web.client.RestTemplate;


/**
 * 设备Controller
 *
 * @author hewenze
 * @date 2020-08-07
 */
@RestController
@Api(value = "设备接口", tags = "设备接口")
@RequestMapping("/system/device")
public class TblDeviceController extends BaseController {
    @Autowired
    private ITblDeviceService tblDeviceService;

    @Autowired
    private TblDeviceMapper tblDeviceMapper;

    @Autowired
    private ApiTokenUtil apiTokenUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrgCodeUtils orgCodeUtils;


    /**
     * 查询设备列表
     */
    @ApiOperation(value = "查询设备列表", notes = "查询设备列表")
    @GetMapping("/list")
    public TableDataInfo list(DevicePoReqDTO devicePoReq) {
        TblDevicePo tblDevicePo = new TblDevicePo().dtoToDo(devicePoReq);
        startPage();
        List<TblDeviceVo> list = tblDeviceService.selectTblDeviceList(tblDevicePo);
        return getDataTable(list);
    }


    /**
     * 查询设备列表
     */
    @ApiOperation(value = "查询单个设备信息", notes = "单个设备信息")
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable String id) {
        TblDeviceVo deviceVo = tblDeviceService.selectById(id);
        return AjaxResult.success(deviceVo);
    }

    /**
     * 通过mac和路数查询设备
     *
     * @param zigbeeMac
     * @param wayNum
     * @return
     */
    @GetMapping("/byMacAndWay")
    public AjaxResult getByMacAndWay(String zigbeeMac, Integer wayNum) {
        TblDeviceVo deviceVo = tblDeviceService.selectByMacAndWay(zigbeeMac,wayNum);
        return AjaxResult.success(deviceVo);
    }

    /**
     * 导出设备列表
     */
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "导出设备列表", notes = "导出设备列表")
    @GetMapping("/export")
    public AjaxResult export(TblDevicePo tblDevicePo, HttpServletRequest request) throws IOException {

        tblDevicePo.setOrganizationCode(orgCodeUtils.getOrgCode(request));
        tblDevicePo.setPageNum(null);
        tblDevicePo.setPageSize(null);
        List<TblDeviceVo> list = tblDeviceService.selectTblDeviceList(tblDevicePo);
        ExcelUtil<TblDeviceVo> util = new ExcelUtil<TblDeviceVo>(TblDeviceVo.class);
        return util.exportExcel(list, "zigbee产品");
    }

    /**
     * 获取设备数量
     */
    @ApiOperation(value = "查询设备数量", notes = "查询设备数量")
    @GetMapping(value = "/getDeviceCount")
    public AjaxResult getDeviceCount(TblDevicePo tblDevicePo, HttpServletRequest request) {
        return AjaxResult.success(tblDeviceService.getDeviceCount(tblDevicePo));
    }

    /**
     * 获取设备状态
     */
    @ApiOperation(value = "查询设备数量", notes = "查询设备数量")
    @GetMapping(value = "/getDeviceAction")
    public AjaxResult getDeviceAction(TblDeviceActionPo tblDeviceActionPo) {
        TblDeviceActionVo deviceAction = tblDeviceMapper.getDeviceAction(tblDeviceActionPo);
        return AjaxResult.success(deviceAction);
    }


    /**
     * 控制设备
     */
    @ApiOperation(value = "控制设备", notes = "控制设备")
    @GetMapping(value = "/cmd")
    public AjaxResult cmd(
            @RequestParam("deviceType") String deviceType,
            @RequestParam("purpose") String purpose,
            @RequestParam("controlParam") String controlParam,

            HttpServletRequest request) {


        String account = orgCodeUtils.getLoginUser(request).getUser().getPassword();
        String password = orgCodeUtils.getLoginUser(request).getUser().getPhonenumber();
        System.out.println(account);
        System.out.println(password);
        String orgCode = "zyzn";
        String type = "manage";
        String apiToken = apiTokenUtil.getApiToken(account, password, orgCode, type);


        String user_url = apiTokenUtil.getUrl() + "/api/command/cmdDeal?deviceType={deviceType}&purpose={purpose}&controlParam={controlParam}";

        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHeaders = new HttpHeaders();
        //user_url = user_url + "account=" + account + "&password=" + password + "&type=" + "manage";
        requestHeaders.add("Authorization", apiToken);

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("deviceType", deviceType);
        paramMap.put("purpose", purpose);
        paramMap.put("controlParam", controlParam);

        org.springframework.http.HttpEntity<String> requestEntity = new org.springframework.http.HttpEntity<String>(null, requestHeaders);
        ResponseEntity<ControllerApiResult> response1 = restTemplate.exchange(user_url, HttpMethod.POST, requestEntity, ControllerApiResult.class, paramMap);
        //String tokenStr = response.getBody().getDataObject().toString();

        String msg = response1.getBody().getMsg();
        if (msg == null || !msg.equals("控制命令已发送！")) {
            return AjaxResult.success("操作失败");
        }
        return AjaxResult.success("操作成功");

    }

    @GetMapping("/listByHomeId")
    public TableDataInfo getDeviceListByHomeId(TblDevicePo tblDevicePo) {
        startPage();
        List<TblDeviceVo> tblDeviceVos = tblDeviceService.selectDeviceListByHomeId(tblDevicePo);
        return getDataTable(tblDeviceVos);
    }

    @Value("${zyzn.device.delete}")
    private String deviceDeleteUrl;

    @DeleteMapping("/delete")
    public AjaxResult deleteDevice(String id, HttpServletRequest request) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("deviceId", id);

        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", request.getHeader("Authorization"));
        httpHeaders.set("organizationCode", orgCodeUtils.getOrgCode(request));

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ControllerResult result = restTemplate.exchange(deviceDeleteUrl, HttpMethod.DELETE, httpEntity, ControllerResult.class).getBody();
        return AjaxResult.success();
    }
}
